package com.exde.wcsiapp.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.exde.wcsiapp.Utils.StringEncrypt;
import com.exde.wcsiapp.Utils.URLUtil;
import com.exde.wcsiapp.gps.AMapLocationForTrajectoryUtil;
import com.exde.wcsiapp.gps.AMapLocationUtil;
import com.exde.wcsiapp.photograph.ImageUtil;
import com.exde.wcsiapp.gps.LocationUtils;
import com.exde.wcsiapp.photograph.PermissionUtil;
import com.exde.wcsiapp.R;
import com.exde.wcsiapp.gps.SendHandlerMessageUtil;
import com.exde.wcsiapp.autoupdate.LoadingService;
import com.exde.wcsiapp.autoupdate.Utils;
import com.exde.wcsiapp.autoupdate.VersionInfoBean;
import com.exde.wcsiapp.photograph.WebChromeClientImpl;
import com.exde.wcsiapp.progress.ZProgressHUD;
import com.exde.wcsiapp.update.DownloadService;
import com.exde.wcsiapp.update.InstallUtil;
import com.exde.wcsiapp.update.SystemManager;
import com.google.gson.Gson;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class MainActivity extends AppCompatActivity implements WebChromeClientImpl.OpenFileChooserCallBack {

    public static String TAG = "MainActivity";

    private Context context;
    private Context mContext;

    private String VersionUrl = URLUtil.VersionUrl;
    private String url = URLUtil.url;

    private WebView web;

    //图片上传
    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private static final int REQUEST_CODE_QRCode = 2;

    private Intent mSourceIntent;
    private ValueCallback<Uri> mUploadMsg;
    public ValueCallback<Uri[]> mUploadMsgForAndroid5;

    // permission Code
    private static final int P_CODE_PERMISSIONS = 101;

    //定位信息
    private static final int P_CODE_TRAJECTORY = 201;
    private AMapLocationUtil mAMapLocationUtil;
    private AMapLocationForTrajectoryUtil mAMapLocationForTrajectoryUtil;

    private int locationForTrajectoryCount = 0;
    private int locationCount = 0;

    //Progress
    private ZProgressHUD mZProgressHUD;

    private VersionInfoBean versionInfoBean;
    private boolean isLoading = false;
    private MyReceive myReceive;
    private String success;

    private Dialog dialog;

    private boolean isSetMapLocation = false;

    //保存cookie
    private SharedPreferences sharedPreferences;
    private Editor editor;

    private DownloadService.DownloadBinder mDownloadBinder;
    private Disposable mDisposable;//可以取消观察者

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mDownloadBinder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mDownloadBinder = null;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this.getApplicationContext();
        mContext = MainActivity.this;

        sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        DownloadService.activity = this;

        Intent intent = new Intent(this, DownloadService.class);
        startService(intent);
        bindService(intent, mConnection, BIND_AUTO_CREATE);//绑定服务

        initView();
        initUtil();
        initUpdate();
        getUserTrajectory();
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(myReceive);//LS:重点！
        progressDismiss();
//        mZProgressHUD = ZProgressHUD.getInstance(this);
//        mZProgressHUD.dismiss();
    }

    public void progressShow() {
        mZProgressHUD = ZProgressHUD.getInstance(this);
        if (!mZProgressHUD.isShowing()) {
            mZProgressHUD.setMessage("加载中");
            mZProgressHUD.setSpinnerType(ZProgressHUD.SIMPLE_ROUND_SPINNER);
            mZProgressHUD.show();
        }
    }

    public void progressSBShow() {
        mZProgressHUD = ZProgressHUD.getInstance(this);
        if (!mZProgressHUD.isShowing()) {
            mZProgressHUD.setMessage("提交中");
            mZProgressHUD.setSpinnerType(ZProgressHUD.SIMPLE_ROUND_SPINNER);
            mZProgressHUD.show();
        }
    }

    public void progressDismiss() {
        mZProgressHUD = ZProgressHUD.getInstance(this);
        if (mZProgressHUD != null && mZProgressHUD.isShowing()) {
            mZProgressHUD.dismiss();
        }
    }

    private void initUtil() {
        SendHandlerMessageUtil.setWebView(web);
        mAMapLocationUtil = new AMapLocationUtil(getApplicationContext());
        mAMapLocationForTrajectoryUtil = new AMapLocationForTrajectoryUtil(getApplicationContext());

    }

    /**
     * 自动更新程序
     */

    private void initUpdate() {
        myReceive = new MyReceive();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.loading_over");
        filter.addAction("android.intent.action.loading");
        registerReceiver(myReceive, filter);
        Log.d(TAG, "initUpdate: isLoading:" + isLoading);
        if (isLoading) {
            Toast.makeText(MainActivity.this, "正在下载...", Toast.LENGTH_SHORT).show();
        } else {
            checkVersion();
        }
    }

    // handler对象，用来接收消息~
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {  //这个是发送过来的消息
            // 处理从子线程发送过来的消息
            int arg1 = msg.arg1;  //获取消息携带的属性值
            int arg2 = msg.arg2;
            int what = msg.what;
            Object result = msg.obj;
            Log.d(TAG, "handleMessage:arg1 " + arg1);
            Log.d(TAG, "handleMessage:arg2 " + arg2);
            Log.d(TAG, "handleMessage:what " + what);
            Log.d(TAG, "handleMessage:result " + result);
            switch (what) {
                case 1: {
                    getVersionInfoFromServer();
                    break;
                }
                case 2: {
                    progressSBShow();
                    break;
                }
                case 3: {
                    progressDismiss();
                    break;
                }
                case 4: {
                    OpenQRCode();
                    break;
                }
                case 5: {
                    Map<String, String> user = (Map<String, String>) result;
                    saveUserInfo(user);
                    break;
                }
                case 6: {
                    delUserInfo();
                    break;
                }
                case 7: {
                    setAboutInfo();
                    break;
                }
                case 8: {
                    Map<String, String> map = (Map<String, String>) result;
                    String packName = map.get("packageName");
                    openApp(packName);

                    break;
                }
            }
        }
    };


    private void setAboutInfo() {
        String version = "1.0.0";
        try {
            version = Utils.getVersionName(this);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        SendHandlerMessageUtil.setVersion(version, Utils.compareVersion(version, versionInfoBean.getVersionName()));
        SendHandlerMessageUtil.setAboutInof();

    }

    private void checkVersion() {

        versionInfoBean = null;
        new Thread() {
            public void run() {
                super.run();
                Message msg = Message.obtain();
                long startTime = System.currentTimeMillis();
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(VersionUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.connect();

                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        InputStream inputStream = conn.getInputStream();

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = inputStream.read(buffer)) != -1) {
                            out.write(buffer, 0, len);
                        }
                        inputStream.close();
                        out.close();

                        String result = out.toString();
                        Log.d(TAG, "VersionResult:" + result);
                        success = null;
                        try {
                            JSONObject jo = new JSONObject(result);
                            success = jo.getString("success");
                            Log.d(TAG, "success:" + success);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if (success.equals("true")) {
                            Gson gson = new Gson();
                            versionInfoBean = gson.fromJson(result, VersionInfoBean.class);
                            msg.what = 1;
                        } else {
                            msg.what = 0;
                        }

                    }
                } catch (MalformedURLException e) {
                    //url错误
                    e.printStackTrace();
                } catch (IOException e) {
                    //网络错误
                    e.printStackTrace();
                } finally {
                    long endTime = System.currentTimeMillis();
                    long timeUsed = endTime - startTime;
                    if (timeUsed < 2000) {
                        try {
                            Thread.sleep(2000 - timeUsed);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        //关闭网络连接
                        conn.disconnect();
                    }
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }


    /**
     * 从服务器获取版本最新的版本信息
     */
    private void getVersionInfoFromServer() {
        versionInfoBean.setPath(getExternalCacheDir() + "/" + versionInfoBean.getVersionName() + ".jpg");
        SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        sharedPreferences.edit().putString("url", versionInfoBean.getDownloadUrl()).commit();
        sharedPreferences.edit().putString("path", versionInfoBean.getPath()).commit();//getExternalCacheDir获取到的路径 为系统为app分配的内存 卸载app后 该目录下的资源也会删除
        //比较版本信息
        try {
            int result = Utils.compareVersion(Utils.getVersionName(this), versionInfoBean.getVersionName());
            if (result == -1) {//不是最新版本
                showDialog();
            }
//            else{
//                Toast.makeText(MainActivity.this,"已经是最新版本",Toast.LENGTH_SHORT).show();
//            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    private void showDialog() {
        dialogShow1();
    }

    /**
     * 自定义布局
     * setView()只会覆盖AlertDialog的Title与Button之间的那部分，而setContentView()则会覆盖全部，
     * setContentView()必须放在show()的后面
     */
    private void dialogShow1() {
        Log.d(TAG, "dialogShow1: show");
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        TextView version, content;
        Button left, right;
        View view = inflater.inflate(R.layout.version_update, null);
        version = (TextView) view.findViewById(R.id.version);
        content = (TextView) view.findViewById(R.id.content);
        left = (Button) view.findViewById(R.id.left);
        right = (Button) view.findViewById(R.id.right);
        content.setText(Html.fromHtml(versionInfoBean.getDesc()));
        version.setText("版本号：" + versionInfoBean.getVersionName());

        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downloadNewVersionFromServer();

            }
        });
        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        if (dialog == null) {
            dialog = builder.create();
        }
        if (!dialog.isShowing()) {
            //dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            dialog.show();
            dialog.getWindow().setContentView(view);//自定义布局应该在这里添加，要在dialog.show()的后面
            //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        } else {
            Log.d(TAG, "dialogShow1: showing");
        }
    }

    /**
     * 自定义布局
     * setView()只会覆盖AlertDialog的Title与Button之间的那部分，而setContentView()则会覆盖全部，
     * setContentView()必须放在show()的后面
     */
    private void dialogShow2() {
        Log.d(TAG, "dialogShow2: show");
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_manage_dialog, null);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        content.setText(Html.fromHtml(versionInfoBean.getDesc()));
        Button btn_sure = (Button) v.findViewById(R.id.dialog_btn_sure);
        Button btn_cancel = (Button) v.findViewById(R.id.dialog_btn_cancel);
        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        if (dialog == null) {
            dialog = builder.create();
        }
        if (!dialog.isShowing()) {
            dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            dialog.show();
            dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
            //dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
//                    Toast.makeText(mContext, "ok", Toast.LENGTH_LONG).show();
                    downloadNewVersionFromServer();
                }
            });
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dialog.dismiss();
//                    Toast.makeText(mContext, "no", Toast.LENGTH_LONG).show();
                }
            });
        } else {
            Log.d(TAG, "dialogShow2: showing");
        }
    }

    /**
     * 启动服务后台下载
     */
//    private void downloadNewVersionFromServer(){
//        if(new File(versionInfoBean.getPath()).exists()){
//            new File(versionInfoBean.getPath()).delete();
//        }
//        Toast.makeText(MainActivity.this,"开始下载...",Toast.LENGTH_SHORT).show();
//        LoadingService.startUploadImg(this);
//    }
    private void downloadNewVersionFromServer() {

        if (mDownloadBinder != null) {
            long downloadId = mDownloadBinder.startDownload(versionInfoBean.getDownloadUrl());
            startCheckProgress(downloadId);
        }
    }

    //开始监听进度
    private void startCheckProgress(long downloadId) {
        Observable
                .interval(100, 200, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
                .filter(times -> mDownloadBinder != null)
                .map(i -> mDownloadBinder.getProgress(downloadId))//获得下载进度
                .takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
                .distinct()//去重复
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MainActivity.ProgressObserver());
    }


    //观察者
    private class ProgressObserver implements Observer<Integer> {

        @Override
        public void onSubscribe(Disposable d) {
            mDisposable = d;
        }

        @Override
        public void onNext(Integer progress) {
        }

        @Override
        public void onError(Throwable throwable) {
//            throwable.printStackTrace();
            Toast.makeText(MainActivity.this, "出错", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onComplete() {
            Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 定义广播接收者 接受下载状态
     */
    public class MyReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.intent.action.loading_over".equals(action)) {
                isLoading = false;
            } else if ("android.intent.action.loading".equals(action)) {
                isLoading = true;
            }
        }
    }

    /**
     * 着色模式
     */
    private void initStatusBarColour(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setStatusBarColourUpperAPI21(color);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setStatusBarColourUpperAPI19(color);
        }
    }

    //Android5.0版本以上
    private void setStatusBarColourUpperAPI21(int color) {
        Window window = getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);


        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        //由于setStatusBarColor()这个API最低版本支持21, 本人的是15,所以如果要设置颜色,自行到style中通过配置文件设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            window.setStatusBarColor(color);
            //window.setStatusBarColor(Color.TRANSPARENT);
        }
        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }
    }

    // Android4.4 - 5.0版本
    private void setStatusBarColourUpperAPI19(int color) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        int statusBarHeight = getStatusBarHeight();

        View mTopView = mContentView.getChildAt(0);
        if (mTopView != null && mTopView.getLayoutParams() != null &&
                mTopView.getLayoutParams().height == statusBarHeight) {
            //避免重复添加 View
            mTopView.setBackgroundColor(color);
            return;
        }
        //使 ChildView 预留空间
        if (mTopView != null) {
            ViewCompat.setFitsSystemWindows(mTopView, true);
        }

        //添加假 View
        mTopView = new View(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
        mTopView.setBackgroundColor(color);
        mContentView.addView(mTopView, 0, lp);

    }

    //获取状态栏高度
    private int getStatusBarHeight() {
        int result = 0;
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = getResources().getDimensionPixelSize(resId);
        }
        return result;
    }

    /**
     * 获取用户轨迹信息
     */
    private void getUserTrajectory() {
        Log.d("ForTrajectory", "getUserTrajectory: ");
        checkPermissionForTrajectory();
    }

    //判断是否授权
    private void checkPermissionForTrajectory() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d("ForTrajectory", "checkPermission: 未授权！");
            ActivityCompat.requestPermissions(this, new String[]{
//                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION}, P_CODE_TRAJECTORY);
        } else {
            Log.d("ForTrajectory", "checkPermission: 已授权！");
            checkIsLocationOpenForTrajectory();
        }
    }

    //判断是否开启定位
    private void checkIsLocationOpenForTrajectory() {
        boolean isOpen = LocationUtils.isOpen(context);
        Log.d("ForTrajectory", "checkIsLocationOpen: " + isOpen);
        if (isOpen) {
            getAMapLocationForTrajectory();
        } else {
            if (locationForTrajectoryCount < 5) {
                locationForTrajectoryCount++;
                checkPermissionForTrajectory();
            } else {
                locationForTrajectoryCount = 0;
                Toast.makeText(MainActivity.this,
                        "请去\"设置\"中开启定位服务功能",
                        Toast.LENGTH_SHORT).show();
            }

        }
    }

    //获取定位信息

    public void getAMapLocationForTrajectory() {
        mAMapLocationForTrajectoryUtil.startLocation();
    }

    /**
     * 获取定位信息
     */
    //判断是否授权
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "checkPermission: 未授权！");
            ActivityCompat.requestPermissions(this, new String[]{
//                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        } else {
            Log.d(TAG, "checkPermission: 已授权！");
            checkIsLocationOpen();
        }
    }

    //判断是否开启定位
    private void checkIsLocationOpen() {
        boolean isOpen = LocationUtils.isOpen(context);
        Log.d(TAG, "checkIsLocationOpen: " + isOpen);
        if (isOpen) {
            getLngAndLat(context);
        } else {
            if (locationCount < 5) {
                locationCount++;
                checkPermission();
            } else {
                locationCount = 0;
                SendHandlerMessageUtil.setAndroidLocation();
                Toast.makeText(MainActivity.this,
                        "请去\"设置\"中开启定位服务功能",
                        Toast.LENGTH_SHORT).show();
            }


        }
    }

    public static Context apkContext;
    public static String apkPath;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkIsLocationOpen();
                }
                break;
            case P_CODE_PERMISSIONS:
                requestResult(permissions, grantResults);
                restoreUploadMsg();
                break;
            case P_CODE_TRAJECTORY:
                checkIsLocationOpenForTrajectory();
                break;
            case 300:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    InstallUtil.install(apkContext, apkPath, false);
                } else {
                    //  引导用户手动开启安装权限
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, 301);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //获取定位信息
    private void getLngAndLat(Context context) {
        getAMapLocation(context);
    }

    public void getAMapLocation(Context context) {
        mAMapLocationUtil.startLocation();
    }

    //初始化
    private void initView() {

        web = (WebView) findViewById(R.id.web);

        WebSettings mWebSettings = web.getSettings();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        mWebSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        mWebSettings.setBuiltInZoomControls(true);
        mWebSettings.setJavaScriptEnabled(true);//支持js 特效
        mWebSettings.setDomStorageEnabled(true);//支持DOM API

        mWebSettings.setAllowFileAccess(true);//允许访问文件

        web.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(TAG, "shouldOverrideUrlLoading: " + url);

                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                } else {

                    if (url.indexOf("login") == -1) {//登录页
                        initCookie(url);
                    }
                    view.loadUrl(url);
                }

                return true;
            }

            //页面加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d(TAG, "onPageFinished: " + url);
                url = url.split("url=")[0];
                url = url.split("#/")[0];
                if (url.indexOf("login") > -1) {//登录页
                    initStatusBarColour(getResources().getColor(R.color.loginColor));
                    Log.d(TAG, "onPageFinished: this Android");
                    SendHandlerMessageUtil.setThisAndroid();
                } else if (url.indexOf("mobileMain") > -1) {//首页
                    initStatusBarColour(getResources().getColor(R.color.indexColor));
                    SendHandlerMessageUtil.setFunction("setLocationIndex");
                    checkPermission();
                    Log.d(TAG, "onPageFinished: this Android");
                    SendHandlerMessageUtil.setThisAndroid();
                } else if (url.indexOf("mapPage") > -1) {
                    Log.d(TAG, "mapPage: mapPagemapPagemapPagemapPagemapPagemapPage");
                    isSetMapLocation = true;
                    initStatusBarColour(getResources().getColor(R.color.otherColor));

                } else {
                    initStatusBarColour(getResources().getColor(R.color.otherColor));
                    Log.d(TAG, "isSetMapLocation: " + isSetMapLocation);
                    if (!isSetMapLocation) {
                        SendHandlerMessageUtil.setFunction("setLocation");
                        checkPermission();
                        Log.d(TAG, "onPageFinished: this Android");
                        SendHandlerMessageUtil.setThisAndroid();
                    } else {
                        isSetMapLocation = false;
                    }
                }

                progressDismiss();
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressShow();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

        });

        web.addJavascriptInterface(new WebEventNew(), "jump");

        //设置上传图片
        web.setWebChromeClient(new WebChromeClientImpl(MainActivity.this));

        initCookie(url);
        web.loadUrl(url);

    }

    //初始化cookie
    private void initCookie(String sURL) {

        Log.d("Cookies", "initCookie begin");
        String dcodeuid = sharedPreferences.getString("userName", null);
        String dcodeupwd = sharedPreferences.getString("userPwd", null);
        Log.d("Cookies", "initCookie: " + dcodeuid + "||" + dcodeupwd);
        if (dcodeuid == null || dcodeupwd == null) {
            return;
        }
        //获取页面的cookie
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //设置给webview
        String dcodeuidCoo = "dcodeuid=" + dcodeuid;
        cookieManager.setCookie(sURL, dcodeuidCoo);
        String dcodeupwdCoo = "dcodeupwd=" + dcodeupwd;
        cookieManager.setCookie(sURL, dcodeupwdCoo);
        CookieSyncManager.getInstance().sync();

        String addedCookie = cookieManager.getCookie(url);
        Log.d("Cookies", "initCookie: " + addedCookie);

    }

    //保存用户信息
    private void saveUserInfo(Map<String, String> user) {
        //将user存到数据库
        String userName = user.get("userName");
        String userPwd = user.get("userPwd");

        try {
            userName = URLEncoder.encode(userName, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Log.d("saveUserInfo", userName + ":" + userPwd);
        sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
        editor.putString("userName", userName).commit();
        editor.putString("userPwd", userPwd).commit();
    }

    //删除用户信息
    private void delUserInfo() {
        //将user存到数据库
        sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
        editor.clear();
        editor.commit();
    }


    private class WebEventNew {
        private Handler webHandler = new Handler();

        public WebEventNew() {
        }

        /**
         * 触发回退按钮
         */
        @JavascriptInterface
        public void WebgoBack() {
            Log.d(TAG, "goBack: this.goBack");
            webHandler.post(new Runnable() {
                @Override
                public void run() {
                    web.goBack();
                }
            });
        }

        /**
         * 重新定位
         */
        @JavascriptInterface
        public void reSetLocation() {
            Log.d(TAG, "goBack: this.reSetLocation");
            checkPermission();
        }

        /**
         * 显示等待框
         */
        @JavascriptInterface
        public void proShow() {
            Log.d(TAG, "this.progressSBShow");
            Message msg = Message.obtain();
            msg.what = 2;
            MainActivity.this.handler.sendMessage(msg);
        }

        /**
         * 隐藏等待框
         */
        @JavascriptInterface
        public void proDismiss() {
            Log.d(TAG, "this.progressDismiss");
            Message msg = Message.obtain();
            msg.what = 3;
            MainActivity.this.handler.sendMessage(msg);

        }

        /**
         * 显示二维码扫描
         */
        @JavascriptInterface
        public void QRCode() {
            Log.d(TAG, "this.QRCode");
            Message msg = Message.obtain();
            msg.what = 4;
            MainActivity.this.handler.sendMessage(msg);

        }

        /**
         * 保存用户基本信息
         */
        @JavascriptInterface
        public void saveUserInfo(String userName, String userPwd) {
            Log.d("saveUserInfo", "this.saveUserInfo " + userName + "==" + userPwd);
            Message msg = Message.obtain();
            msg.what = 5;
            Map<String, String> user = new HashMap<String, String>();
            String newUserPwd = StringEncrypt.getSHA256StrJava(userPwd);
            user.put("userName", userName);
            user.put("userPwd", newUserPwd);

            msg.obj = user;

            MainActivity.this.handler.sendMessage(msg);

        }

        /**
         * 保存用户基本信息
         */
        @JavascriptInterface
        public void delUserInfo() {
            Log.d("delUserInfo", "this.delUserInfo ");
            Message msg = Message.obtain();
            msg.what = 6;
            MainActivity.this.handler.sendMessage(msg);
        }

        /**
         * 获取版本号
         */
        @JavascriptInterface
        public void getAbout() {
            Log.d(TAG, "this.getAbout");
            Message msg = Message.obtain();
            msg.what = 7;
            MainActivity.this.handler.sendMessage(msg);
        }


        /**
         * 启动app
         */
        @JavascriptInterface
        public void openApp(String packageName) {
            Log.d(TAG, "this.openApp :" + packageName);
            Message msg = Message.obtain();
            Map<String, String> map = new HashMap<String, String>();
            map.put("packageName", packageName);
            msg.obj = map;
            msg.what = 8;
            MainActivity.this.handler.sendMessage(msg);

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack()) {
            web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 图片上传
     */

    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        // TODO 自动生成的方法存根
        mUploadMsgForAndroid5 = filePathCallback;
        return true;
    }

    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMsg = uploadMsg;

        showOptions();
    }

    @Override
    public boolean openFileChooserCallBackAndroid5
            (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        mUploadMsgForAndroid5 = filePathCallback;
        showOptions();

        return true;
    }

    public void showOptions() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setOnCancelListener(new DialogOnCancelListener());

        alertDialog.setTitle("请选择操作");
        // gallery, camera.
        String[] options = {"相册", "拍照"};

        alertDialog.setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            if (PermissionUtil.isOverMarshmallow()) {
                                if (!PermissionUtil.isPermissionValid(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                                    Toast.makeText(MainActivity.this,
                                            "请去\"设置\"中开启本应用的图片媒体访问权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }

                            }

                            try {
                                if (Build.VERSION.SDK_INT >= 23) {
                                    mSourceIntent = ImageUtil.choosePicture();
                                } else {
                                    mSourceIntent = ImageUtil.choosePicture();
                                }

                                startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this,
                                        "请去\"设置\"中开启本应用的图片媒体访问权限",
                                        Toast.LENGTH_SHORT).show();
                                restoreUploadMsg();
                            }

                        } else {
                            if (PermissionUtil.isOverMarshmallow()) {
                                if (!PermissionUtil.isPermissionValid(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    Toast.makeText(MainActivity.this,
                                            "请去\"设置\"中开启本应用的图片媒体访问权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }

                                if (!PermissionUtil.isPermissionValid(MainActivity.this, Manifest.permission.CAMERA)) {
                                    Toast.makeText(MainActivity.this,
                                            "请去\"设置\"中开启本应用的相机权限",
                                            Toast.LENGTH_SHORT).show();

                                    restoreUploadMsg();
                                    requestPermissionsAndroidM();
                                    return;
                                }
                            }

                            try {
                                if (Build.VERSION.SDK_INT >= 23) {
                                    mSourceIntent = ImageUtil.takeBigPicture2(MainActivity.this);
                                } else {
                                    mSourceIntent = ImageUtil.takeBigPicture();
                                }

                                startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);

                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this,
                                        "请去\"设置\"中开启本应用的相机和图片媒体访问权限",
                                        Toast.LENGTH_SHORT).show();

                                restoreUploadMsg();
                            }
                        }
                    }
                }
        );

        alertDialog.show();
    }


    //解决选择文件后按钮失效问题，需要覆写onActivityResult方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == REQUEST_CODE_IMAGE_CAPTURE || requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (resultCode != Activity.RESULT_OK) {
                if (mUploadMsg != null) {
                    mUploadMsg.onReceiveValue(null);
                }

                if (mUploadMsgForAndroid5 != null) {         // for android 5.0+
                    mUploadMsgForAndroid5.onReceiveValue(null);
                }
                return;
            }
        }
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE: {
                try {
                    if (Build.VERSION.SDK_INT >= 23) {
                        if (mUploadMsgForAndroid5 == null) {
                            return;
                        }

                        //String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, intent);

//                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
//                            break;
//                        }
                        //Uri uri = FileProvider.getUriForFile(context, "com.exde.wcsiapp.fileProvider", new File(sourcePath));

                        Uri uri = ImageUtil.retrievePath();
                        mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});

                    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsg == null) {
                            return;
                        }

                        String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, intent);

                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            break;
                        }
                        Uri uri = Uri.fromFile(new File(sourcePath));
                        mUploadMsg.onReceiveValue(uri);

                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                            return;
                        }

                        String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, intent);

                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            break;
                        }
                        Uri uri = Uri.fromFile(new File(sourcePath));
                        mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }

            case REQUEST_CODE_PICK_IMAGE: {
                try {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsg == null) {
                            return;
                        }

                        String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, intent);

                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            break;
                        }
                        Uri uri = Uri.fromFile(new File(sourcePath));
                        mUploadMsg.onReceiveValue(uri);

                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (mUploadMsgForAndroid5 == null) {        // for android 5.0+
                            return;
                        }

                        String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, intent);

                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            break;
                        }
                        Uri uri = Uri.fromFile(new File(sourcePath));
                        mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case REQUEST_CODE_QRCode: {
                if (intent != null) {
                    Bundle bundle = intent.getExtras();
                    String Url = null;
                    if (bundle != null) {
                        Url = bundle.getString("result");
                        Log.d("QQQ", "handleDecode: " + Url);
                        web.loadUrl(Url);
                    }
                }
                break;
            }
            case 301: {
                checkIsAndroidO();
                break;
            }
        }

    }

    /*
     *
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidO() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = getPackageManager().canRequestPackageInstalls();
            if (b) {
                InstallUtil.install(apkContext, apkPath, false);
            } else {
                //请求安装未知应用来源的权限
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 300);
            }
        } else {
            InstallUtil.install(apkContext, apkPath, false);
        }
    }

    private class DialogOnCancelListener implements DialogInterface.OnCancelListener {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            restoreUploadMsg();
        }
    }

    private void restoreUploadMsg() {
        if (mUploadMsg != null) {
            mUploadMsg.onReceiveValue(null);
            mUploadMsg = null;

        } else if (mUploadMsgForAndroid5 != null) {
            mUploadMsgForAndroid5.onReceiveValue(null);
            mUploadMsgForAndroid5 = null;
        }
    }

    private void requestPermissionsAndroidM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> needPermissionList = new ArrayList<>();
            needPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            needPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            needPermissionList.add(Manifest.permission.CAMERA);

            PermissionUtil.requestPermissions(MainActivity.this, P_CODE_PERMISSIONS, needPermissionList);

        } else {
            return;
        }
    }

    public void requestResult(String[] permissions, int[] grantResults) {
        ArrayList<String> needPermissions = new ArrayList<String>();

        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                if (PermissionUtil.isOverMarshmallow()) {

                    needPermissions.add(permissions[i]);
                }
            }
        }

        if (needPermissions.size() > 0) {
            StringBuilder permissionsMsg = new StringBuilder();

            for (int i = 0; i < needPermissions.size(); i++) {
                String strPermissons = needPermissions.get(i);

                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_storage));

                } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_storage));

                } else if (Manifest.permission.CAMERA.equals(strPermissons)) {
                    permissionsMsg.append("," + getString(R.string.permission_camera));

                }
            }

            String strMessage = "请允许使用\"" + permissionsMsg.substring(1).toString() + "\"权限, 以正常使用APP的所有功能.";

            Toast.makeText(MainActivity.this, strMessage, Toast.LENGTH_SHORT).show();

        } else {

            return;
        }
    }

    private void OpenQRCode() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            //Intent intent = new Intent(this, CaptureActivity.class);
            Intent intent = new Intent(this, com.exde.wcsiapp.zxing.view.android.CaptureActivity.class);
//            startActivity(intent);
            startActivityForResult(intent, REQUEST_CODE_QRCode);
        }
    }

    private void openApp(String packagename) {
        doStartApplicationWithPackageName(packagename);
    }

    private void doStartApplicationWithPackageName(String packagename) {


        PackageManager packageManager = getPackageManager();
        Intent intent = new Intent();
        intent = packageManager.getLaunchIntentForPackage(packagename);
        if (intent == null) {
            Toast.makeText(MainActivity.this, "未安装", Toast.LENGTH_LONG).show();
        } else {
            startActivity(intent);
        }


//        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
//        PackageInfo packageinfo = null;
//        try {
//            packageinfo = getPackageManager().getPackageInfo(packagename, 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        if (packageinfo == null) {
//            return;
//        }
//
//        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        resolveIntent.setPackage(packageinfo.packageName);
//
//        // 通过getPackageManager()的queryIntentActivities方法遍历
//        List<ResolveInfo> resolveinfoList = getPackageManager()
//                .queryIntentActivities(resolveIntent, 0);
//
//        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
//        if (resolveinfo != null) {
//            // packagename = 参数packname
//            String packageName = resolveinfo.activityInfo.packageName;
//            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
//            String className = resolveinfo.activityInfo.name;
//            // LAUNCHER Intent
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//
//            // 设置ComponentName参数1:packagename参数2:MainActivity路径
//            ComponentName cn = new ComponentName(packageName, className);
//
//            intent.setComponent(cn);
//            startActivity(intent);
//        }
    }

}
